﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Foundation.EntityFrameworkCore;
using mozhi.smarterp.Foundation.OperationLogTemplates;
using mozhi.smarterp.Foundation.OperationLogTemplates.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Foundation.Repositories
{
    public class OperationTemplateRepository : EfCoreRepository<FoundationDbContext, OperationLogTemplate, Guid>, IOperationLogTemplateRepository
    {
        public OperationTemplateRepository(IDbContextProvider<FoundationDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<OperationLogTemplate> FindAsync(string code)
        {
            var dbContext = await GetDbContextAsync();

            var template = await dbContext.Set<OperationLogTemplate>().Include(x => x.Items).FirstOrDefaultAsync(x => x.Code == code);

            return template;
        }

        public async Task<long> GetCountAsync(string code, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var result = await dbContext.Set<OperationLogTemplate>().AsNoTracking().WhereIf(!code.IsNullOrEmpty(), x => x.Code == code).CountAsync();

            return result;
        }

        public async Task<List<OperationLogTemplate>> GetPagedListAsync(int skipCount, int maxResultCount, string sorting, string code, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var result = await dbContext.Set<OperationLogTemplate>().AsNoTracking()
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .Page(skipCount, maxResultCount)
                .ToListAsync();

            return result;
        }
    }
}
